import axios from 'axios'

const apiClient = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
})

// 打印请求日志
console.log('API 客户端初始化，基础URL：', '/api')

// 添加请求拦截器，自动添加token到请求头
apiClient.interceptors.request.use(
  config => {
    // 从 localStorage 获取最新的令牌
    const token = localStorage.getItem('token')
    if (token) {
      // 确保每次请求都使用最新的令牌
      config.headers['Authorization'] = `Bearer ${token}`
    }

    // 打印请求信息，包括请求头中的token
    console.log(`发送请求: ${config.method.toUpperCase()} ${config.url}`, {
      headers: {
        ...config.headers,
        Authorization: config.headers.Authorization ? `${config.headers.Authorization.substring(0, 20)}...` : 'none'
      },
      data: config.data
    })

    return config
  },
  error => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 添加响应拦截器
apiClient.interceptors.response.use(
  response => {
    console.log(`响应成功: ${response.config.method.toUpperCase()} ${response.config.url}`, {
      status: response.status,
      data: response.data
    })
    return response
  },
  error => {
    console.error('API 请求错误:', {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      data: error.response?.data,
      message: error.message
    })

    // 如果是 401 或 422 错误，可能是JWT认证问题
    if (error.response?.status === 401 || error.response?.status === 422) {
      console.error(`${error.response?.status} 错误:`, error.response?.data)

      // 如果是修改密码请求
      if (error.config.url.includes('/auth/change-password')) {
        // 如果是401错误，可能是当前密码错误
        if (error.response?.status === 401 && error.response?.data?.message === 'Current password is incorrect!') {
          error.response.data = { message: '当前密码错误' }
          return Promise.reject(error)
        }
        // 其他情况可能是认证问题
        error.response.data = { message: '认证失败，请重新登录后再试' }
      }
      return Promise.reject(error)
    }

    // 如果是登录请求，返回错误
    if (error.config.url.includes('/auth/login')) {
      return Promise.reject(error)
    }

    // 如果是获取当前用户信息的请求，返回错误
    if (error.config.url.includes('/auth/me')) {
      return Promise.reject(error)
    }

    // 如果是修改密码请求，返回错误
    if (error.config.url.includes('/auth/change-password')) {
      console.error('修改密码失败:', error.response?.status, error.response?.data)
      return Promise.reject(error)
    }

    // 如果是用户管理相关的请求，返回错误
    if (error.config.url.includes('/auth/users')) {
      console.error('获取用户列表失败:', error.response?.status, error.response?.data)
      return Promise.reject(error)
    }

    // 如果是角色管理相关的请求，返回错误
    if (error.config.url.includes('/auth/roles')) {
      console.error('获取角色列表失败:', error.response?.status, error.response?.data)
      return Promise.reject(error)
    }

    // 如果是权限管理相关的请求，返回错误
    if (error.config.url.includes('/auth/permissions')) {
      console.error('获取权限列表失败:', error.response?.status, error.response?.data)
      return Promise.reject(error)
    }

    // 对于其他请求，返回一个空的数据对象，避免前端报错
    return Promise.resolve({
      data: error.config.url.includes('equipment') ? { equipment: [] } :
            error.config.url.includes('speed-trend') ? { } :
            error.config.url.includes('shift-production') ? [] :
            error.config.url.includes('device-status') ? { } :
            error.config.url.includes('alarm-ranking') ? [] :
            error.config.url.includes('operator-efficiency') ? [] :
            error.config.url.includes('real-time-production') ? { } :
            error.config.url.includes('realtime-status') ? { data: [] } : {}
    })
  }
)

export default {
  // Auth endpoints
  login(username, password) {
    return apiClient.post('/auth/login', { username, password })
  },

  register(userData) {
    return apiClient.post('/auth/register', userData)
  },

  getCurrentUser() {
    return apiClient.get('/auth/me')
  },

  refreshToken(username) {
    return apiClient.post('/auth/refresh', { username })
  },

  changePassword(currentPassword, newPassword) {
    // 使用默认的 axios 实例，它会自动使用拦截器中的令牌
    console.log('Change password request with current password:', currentPassword)

    // 从 localStorage 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    const username = userInfo.username || 'admin'
    console.log('Using username for password change:', username)

    return apiClient.post('/auth/change-password', {
      username: username,
      current_password: currentPassword,
      new_password: newPassword
    })
  },

  // User management endpoints
  getUsers() {
    return apiClient.get('/auth/users')
  },

  getUser(userId) {
    return apiClient.get(`/auth/users/${userId}`)
  },

  updateUser(userId, userData) {
    return apiClient.put(`/auth/users/${userId}`, userData)
  },

  deleteUser(userId) {
    return apiClient.delete(`/auth/users/${userId}`)
  },

  // Role management endpoints
  getRoles() {
    return apiClient.get('/auth/roles')
  },

  createRole(roleData) {
    return apiClient.post('/auth/roles', roleData)
  },

  updateRole(roleId, roleData) {
    return apiClient.put(`/auth/roles/${roleId}`, roleData)
  },

  deleteRole(roleId) {
    return apiClient.delete(`/auth/roles/${roleId}`)
  },

  // Permission endpoints
  getPermissions() {
    return apiClient.get('/auth/permissions')
  },

  // Dashboard endpoints
  getDashboardSummary() {
    return apiClient.get('/dashboard/summary')
  },

  getProductionHistory(period = 'day') {
    return apiClient.get(`/dashboard/production-history?period=${period}`)
  },

  getDeviceStatus() {
    return apiClient.get('/dashboard/device-status')
  },

  getProductionBatches(status) {
    const params = status ? `?status=${status}` : ''
    return apiClient.get(`/dashboard/batches${params}`)
  },

  // Device data endpoints
  getDevices() {
    return apiClient.get('/device-data/devices')
  },

  getDevice(deviceId) {
    return apiClient.get(`/device-data/devices/${deviceId}`)
  },

  getDeviceData(deviceId, limit = 100) {
    const params = deviceId ? `?device_id=${deviceId}&limit=${limit}` : `?limit=${limit}`
    return apiClient.get(`/device-data/${params}`)
  },

  // Create a new device
  createDevice(deviceData) {
    return apiClient.post('/device-data/devices', deviceData)
  },

  // Update an existing device
  updateDevice(deviceId, deviceData) {
    return apiClient.put(`/device-data/devices/${deviceId}`, deviceData)
  },

  // This would typically be called by the devices, not the dashboard
  // But included here for testing purposes
  sendDeviceData(data) {
    return apiClient.post('/device-data/', data)
  },

  // Test data endpoints
  getTestData(page = 1, perPage = 100, filters = {}) {
    let params = `?page=${page}&per_page=${perPage}`
    if (filters.equipment) params += `&equipment=${filters.equipment}`
    if (filters.operator) params += `&operator=${filters.operator}`
    if (filters.shiftType) params += `&shift_type=${filters.shiftType}`
    return apiClient.get(`/test-data/${params}`)
  },

  getEquipmentList() {
    return apiClient.get('/test-data/equipment')
  },

  getOperatorsList() {
    return apiClient.get('/test-data/operators')
  },

  getSpeedTrend(equipment) {
    const params = equipment ? `?equipment=${equipment}` : ''
    return apiClient.get(`/test-data/speed-trend${params}`)
  },

  getShiftProduction() {
    return apiClient.get('/test-data/shift-production')
  },

  getDeviceStatusDistribution(equipment) {
    const params = equipment ? `?equipment=${equipment}` : ''
    return apiClient.get(`/test-data/device-status${params}`)
  },

  getAlarmRanking() {
    return apiClient.get('/test-data/alarm-ranking')
  },

  getOperatorEfficiency() {
    return apiClient.get('/test-data/operator-efficiency')
  },

  getRealTimeProduction(equipment, window = 15) {
    let params = '?'
    if (equipment) params += `equipment=${equipment}&`
    params += `window=${window}`
    return apiClient.get(`/test-data/real-time-production${params}`)
  },

  getRealtimeStatus(filters = {}) {
    let params = '?'
    if (filters.equipment) params += `equipment=${filters.equipment}&`
    if (filters.status) params += `status=${filters.status}&`
    if (filters.running) params += `running=${filters.running}&`
    if (filters.alarm) params += `alarm=${filters.alarm}&`
    // 删除最后一个&如果存在
    params = params === '?' ? '' : params.endsWith('&') ? params.slice(0, -1) : params
    return apiClient.get(`/test-data/realtime-status${params}`)
  },

  // Employee management endpoints
  getEmployees(page = 1, perPage = 10, filters = {}) {
    let params = `?page=${page}&per_page=${perPage}`
    if (filters.department_id) params += `&department_id=${filters.department_id}`
    if (filters.status) params += `&status=${filters.status}`
    if (filters.search) params += `&search=${filters.search}`
    return apiClient.get(`/employees/${params}`)
  },

  getEmployee(employeeId) {
    return apiClient.get(`/employees/${employeeId}`)
  },

  createEmployee(employeeData) {
    return apiClient.post('/employees/', employeeData)
  },

  updateEmployee(employeeId, employeeData) {
    return apiClient.put(`/employees/${employeeId}`, employeeData)
  },

  deleteEmployee(employeeId) {
    return apiClient.delete(`/employees/${employeeId}`)
  },

  // Department management endpoints
  getDepartments() {
    return apiClient.get('/employees/departments')
  },

  createDepartment(departmentData) {
    return apiClient.post('/employees/departments', departmentData)
  },

  updateDepartment(departmentId, departmentData) {
    return apiClient.put(`/employees/departments/${departmentId}`, departmentData)
  },

  deleteDepartment(departmentId) {
    return apiClient.delete(`/employees/departments/${departmentId}`)
  }
}

